package com.design.sys.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.design.common.JsonResult;
import com.design.common.utils.JwtUtil;
import com.design.sys.entity.User;
import com.design.sys.entity.UserRole;
import com.design.sys.mapper.UserMapper;
import com.design.sys.mapper.UserRoleMapper;
import com.design.sys.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yang
 * @since 2023-06-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }


    @Override
    public Map<String, Object> login(User user) {
        //判断用户名密码是否相等
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper();
        //eq(数据库数据，前台传入数据)
        wrapper.eq(User::getUsername,user.getUsername());
        User loginUser = this.getOne(wrapper);
        //结果不为空，斌且传入的密码和数据库加密后的密码匹配，则生成token,并将用户传入redis
        if(loginUser != null && passwordEncoder.matches(user.getPassword(),loginUser.getPassword())){
            //jwt
            loginUser.setPassword(null);
            String jwtUtilToken = jwtUtil.createToken(loginUser);
            //String key = "user:" + UUID.randomUUID();
            Map<String, Object> data = new HashMap<>();
            data.put("token", jwtUtilToken);    // 待优化，最终方案jwt
            //数据存入redis
            //loginUser.setPassword(null);
            //redisTemplate.opsForValue().set(key,loginUser,30, TimeUnit.MINUTES);
            return data;
        }
        return null;
        /*                //判断用户名密码是否相等_数据库密码未加密存储
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper();
        //eq(数据库数据，前台传入数据)
        wrapper.eq(User::getUsername,user.getUsername());
        wrapper.eq(User::getPassword,user.getPassword());
        User loginUser = this.getOne(wrapper);
        if(loginUser != null){
            Map<String, Object> data = new HashMap<>();
            String key = "user:" + UUID.randomUUID();
            data.put("token", key);    // 待优化，最终方案jwt
            loginUser.setPassword(null);
            //数据存入redis
            redisTemplate.opsForValue().set(key,loginUser,30, TimeUnit.MINUTES);
            return data;
        }
        return null;*/
    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        //根据token获取用户信息 redis获取
        //Object obj = redisTemplate.opsForValue().get(token);
        User loginUser=null;
        try {
            loginUser = jwtUtil.parseToken(token, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //反序列化
        if (loginUser!=null){
            //User loginUser = JSON.parseObject(JSON.toJSONString(user), User.class);
            HashMap<String, Object> data = new HashMap<>();
            data.put("name",loginUser.getUsername());
            data.put("ayatar",loginUser.getAvatar());
            //角色
            List<String> roleList = userMapper.getRoleNameByUserId(loginUser.getId());
            data.put("roles",roleList);
            return data;
        }
        return null;
    }

    @Override
    public void logout(String token) {

        //redisTemplate.delete(token);
    }

    @Override
    @Transactional
    public void addUser(User user) {
        //user表添加
        this.save(user);
        //role_menu表添加
        List<Integer> roleIdList = user.getRoleIdList();
        if (null != roleIdList){
            for (Integer roleId : roleIdList) {
                userRoleMapper.insert(new UserRole(null,user.getId(),roleId));
            }
        }


    }

    /*获取用户，并且回显角色权限*/
    @Override
    @Transactional
    public User getUserById(Integer id) {
        //通过id查询user用户
        User user = this.getById(id);
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        //找到UserRole中的role_id，并生成列表
        List<UserRole> userRoleList = userRoleMapper.selectList(wrapper);
        List<Integer> roleIdList = userRoleList.stream().map(userRole -> {
            return userRole.getRoleId();
        }).collect(Collectors.toList());
        user.setRoleIdList(roleIdList);
        return user;
    }

    /*编辑用户*/
    @Override
    @Transactional
    public void updateUser(User user) {
        //更新user
        this.updateById(user);
        //清除原有角色
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, user.getId());
        userRoleMapper.delete(wrapper);
        //设置新角色
        List<Integer> roleIdList = user.getRoleIdList();
        if (null != roleIdList) {
            for (Integer roleId : roleIdList) {
                userRoleMapper.insert(new UserRole(null, user.getId(), roleId));
            }
        }
    }

    @Override
    @Transactional
    public void deleteUserById(Integer id) {
        //通过id删除user用户
        this.removeById(id);
        //删除userRole表
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        userRoleMapper.delete(wrapper);
    }
}
